# -*- coding: utf-8 -*-            
# @Time : 2025/7/25 13:02
# @FileName: utils.py
# @Target:
import copy
import json, codecs, time, os, requests, logging
from logging.handlers import RotatingFileHandler
from pprint import pprint

from dotenv import load_dotenv

from llm import tool
from llm import quality_analyze
from llm import cuzu
from llm import translator
from llm import simplenlp

load_dotenv()


class CONFIGS:
    def __init__(self):
        self.rabbitmq_user = os.getenv('RABBITMQ_USER', 'idmi')
        self.rabbitmq_pw = os.getenv('RABBITMQ_PW', 'idmi')
        if self.is_docker_env:
            self.rabbitmq_ip = os.getenv('RABBITMQ_IP_DOCKER', '172.17.0.1')
        else:
            self.rabbitmq_ip = os.getenv('RABBITMQ_IP_LOCALHOST', '0.0.0.0')
        self.rabbitmq_web_port = os.getenv('RABBITMQ_WEB_PORT', 15672)
        self.rabbitmq_data_port = os.getenv('RABBITMQ_DATA_PORT', 5672)
        self.rabbitmq_vhost = os.getenv('RABBITMQ_VHOST', '/')
        self.rabbitmq_exchange = os.getenv('RABBITMQ_EXCHANGE', 'idmi')
        self.rabbitmq_connection_attempts = os.getenv('RABBITMQ_CONNECTION_ATTEMPTS', 5)
        self.rabbitmq_retry_delay = os.getenv('RABBITMQ_RETRY_DELAY', 5)
        self.rabbitmq_queue = os.getenv('RABBITMQ_QUEUE', 'idmi')
        self.rabbitmq_routing_key = os.getenv('RABBITMQ_ROUTING_KEY', 'idmi')
        self.translate_url = os.getenv('TRANSLATE_URL', 'http://152.32.135.145:17300/translate')
        self.translate_sk = os.getenv('TRANSLATE_SK', 'liuyang177')
        self.label_url = os.getenv('LABEL_URL', 'http://106.75.44.18:7800')
        self.data_processing_url = os.getenv('DATA_PREPROCESSING_URL', 'http://106.75.44.18:7900')
        self.saved_data_host = os.getenv('SAVED_DATA_HOST', 'http://45.249.247.52:8000')

    @property
    def is_docker_env(self):
        return os.environ.get('DOCKER_CONTAINER') is not None

    @property
    def maixun_fid_info(self):
        # url = os.path.join(self.label_url, 'Maixun_fid_info')
        url = "http://106.75.44.18:7800/Maixun_fid_info"
        res = requests.get(
            url=url
        )
        with codecs.open(filename='configs/maixun_fid_20250717.json',
                         mode='w', encoding='utf-8') as fw:
            json.dump(obj=res.json(), fp=fw, ensure_ascii=False, indent=4)
        return res.json()

    @property
    def maixun_domain_mapping(self):
        url = "http://106.75.44.18:7800/maixun_domain_mapping"
        res = requests.get(
            url=url
        )
        with codecs.open(filename='configs/maixun_domain.json',
                         mode='w', encoding='utf-8') as fw:
            json.dump(obj=res.json(), fp=fw, ensure_ascii=False, indent=4)
        return res.json()

    @property
    def feeling_labels(self):
        url = "http://106.75.44.18:7800/feeling_labels"
        res = requests.get(
            url=url
        )
        with codecs.open(filename='configs/cuzu_labels_20250627.json',
                         mode='w', encoding='utf-8') as fw:
            json.dump(obj=res.json(), fp=fw, ensure_ascii=False, indent=4)
        return res.json()

    @property
    def quality_labels(self):
        url = "http://106.75.44.18:7800/quality_labels"
        res = requests.get(
            url=url
        )
        with codecs.open(filename='configs/quality_labels_20250627.json',
                         mode='w', encoding='utf-8') as fw:
            json.dump(obj=res.json(), fp=fw, ensure_ascii=False, indent=4)
        return res.json()

    @property
    def idmi_crawler_modelname_mapping(self):
        url = "http://106.75.44.18:7800/idmi_crawler_modelname_mapping"
        res = requests.get(
            url=url
        )
        with codecs.open(filename='configs/idmi-crawled-modelName2fid.json',
                         mode='w', encoding='utf-8') as fw:
            json.dump(obj=res.json(), fp=fw, ensure_ascii=False, indent=4)
        return res.json()

    @property
    def sourceId2websites_Response(self):
        url = "http://106.75.44.18:7800/sourceId2websites_Response"
        res = requests.get(
            url=url
        )
        with codecs.open(filename='configs/sourceId2websites.json',
                         mode='w', encoding='utf-8') as fw:
            json.dump(obj=res.json(), fp=fw, ensure_ascii=False, indent=4)
        return res.json()


configs = CONFIGS()

is_docker_env = configs.is_docker_env
maixun_fid_info = configs.maixun_fid_info
maixun_domain_mapping = configs.maixun_domain_mapping
feeling_labels = configs.feeling_labels
quality_labels = configs.quality_labels
idmi_crawler_modelname_mapping = configs.idmi_crawler_modelname_mapping
sourceId2websites_Response = configs.sourceId2websites_Response


def log_setup(log_folder, log_filename):
    def check_log_folder(folder):
        if os.path.exists(folder) and os.path.isdir(folder):
            ...
        else:
            os.mkdir(folder)

    check_log_folder(log_folder)

    formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')

    def setRotatingRootLogger(filename, level=logging.INFO):
        handler = RotatingFileHandler(
            filename,
            encoding='UTF-8',
            maxBytes=1000000,
            backupCount=5
        )
        handler.setFormatter(formatter)
        logger = logging.getLogger()
        logger.setLevel(level)
        logger.addHandler(handler)

    setRotatingRootLogger(filename=log_filename)




def purchase_year_analyze(
        customer_voice,
        current_date=''
):
    purchase_year = tool.purchase_year(
        customer_voice=customer_voice,
        content=current_date
    )
    return purchase_year


def idmi_crawled_complaints_map2fid(sourceId, OEM_src, ModelName_src) -> int:
    modelname2fid = copy.deepcopy(configs.idmi_crawler_modelname_mapping)
    if OEM_src in modelname2fid[sourceId].keys():
        if ModelName_src in modelname2fid[sourceId][OEM_src]:
            return modelname2fid[sourceId][OEM_src][ModelName_src]

    else:
        return 0


def translate_sent(sentence):
    return translator.translate_util_zh2en(title=sentence, text='')['title_en']




class QualityLabel2IntValue:
    def __init__(self):
        self._quality_labels_1_grade = {}
        self._quality_labels_2_grade = {}
        self._quality_labels_3_grade = {}
        for ITEMS_LIST in quality_labels:
            quality_label_1 = ITEMS_LIST['quality_label_1']
            quality_label_1_int_value = ITEMS_LIST['int_value']
            self._quality_labels_1_grade[quality_label_1] = quality_label_1_int_value
            ITEMS = ITEMS_LIST['items']
            for ITEM in ITEMS:
                quality_label_2 = ITEM['quality_label_2']
                quality_label_2_int_value = ITEM['int_value']
                self._quality_labels_2_grade[quality_label_2] = quality_label_2_int_value
                items = ITEM['items']
                for item in items:
                    quality_label_3 = item['quality_label_3']
                    quality_label_3_int_value = item['int_value']
                    self._quality_labels_3_grade[quality_label_3] = quality_label_3_int_value

    @property
    def quality_labels_1_grade(self):
        return self._quality_labels_1_grade

    @property
    def quality_labels_2_grade(self):
        return self._quality_labels_2_grade

    @property
    def quality_labels_3_grade(self):
        return self._quality_labels_3_grade


quality_label2int_value = QualityLabel2IntValue()




def sentiment2intvalue(sentiment) -> int :
    if isinstance(sentiment, str) :
        try:
            sentiment = int(sentiment[-1])
            return sentiment
        except Exception as e:
            return 3
    else:
        return 3


def quality_label2int_label(_complaint_tags) :
    '''
    将Quality Label从文字转换为纯数字
    '''
    complaint_tags = []
    for tag in _complaint_tags:
        quality_1 = tag['quality_1']
        quality_2 = tag['quality_2']
        quality_3 = tag['quality_3']

        quality_1_int_value = quality_label2int_value.quality_labels_1_grade[quality_1]
        quality_2_int_value = quality_label2int_value.quality_labels_2_grade[quality_2]
        quality_3_int_value = quality_label2int_value.quality_labels_3_grade[quality_3]

        content_list_zh = tag['content_list']
        content_list_en = []

        for content in content_list_zh :
            content_en = translator.translate_util_zh2en(title=content, text='')['title_en']
            content_list_en.append(content_en)
        sentiment = sentiment2intvalue(tag['sentiment'])
        complaint_tags.append({
            'quality_1': quality_1,
            'quality_2': quality_2,
            'quality_3': quality_3,
            'quality_1_int_value': quality_1_int_value,
            'quality_2_int_value': quality_2_int_value,
            'quality_3_int_value': quality_3_int_value,
            'content_list_zh': content_list_zh,
            'content_list_en': content_list_en,
            'sentiment': sentiment
        })
    return complaint_tags


def quality_preprocessing(title_zh, text_zh):
    customer_voice = title_zh + text_zh
    _complaint_tags = quality_analyze.complaint_analysis(
        customer_voice=customer_voice
    )
    complaint_tags = quality_label2int_label(_complaint_tags)
    return complaint_tags








